<script>
import TestHeader from './components/TestHeader'
import TestList from './components/TestList'
import TestFooter from './components/TestFooter'

export default {
  name: "App",
  components: {
    TestHeader,
    TestList,
    TestFooter,
  },
  data() {
    return {
      todoList: [],
    }
  },
  methods: {
    addTodo(todo) {
      this.todoList.push(todo)
    },
    deleteTodo(id) {
      this.todoList = this.todoList.filter(todo => todo.id !== id);
    },
    clearDone() {
      this.todoList = this.todoList.filter(todo => todo.done === false);
    },
    changeAll(value) {
      console.log(value)
      this.todoList = this.todoList.map(todo => {
        todo.done = value;
        return todo;
      })
    },
    doneEdit(id, text) {
      this.todoList = this.todoList.map(todo => {
        if (todo.id === id) {
          todo.text = text;
        }
        return todo;
      })
    },
    changeStatus(id) {
      this.todoList = this.todoList.map(todo => {
        if (todo.id === id) {
          todo.done = !todo.done;
        }
        return todo;
      })
    },
  },
  mounted() {
    this.todoList = JSON.parse(localStorage.getItem('todoList')) || [];
    this.$bus.$on('addTodo', this.addTodo)
    this.$bus.$on('deleteTodo', this.deleteTodo)
    this.$bus.$on('clearDone', this.clearDone)
    this.$bus.$on('changeAll', this.changeAll)
    this.$bus.$on('doneEdit', this.doneEdit)
    this.$bus.$on('changeStatus', this.changeStatus)
  },
  beforeDestroy() {
    this.$off('addTodo')
    this.$off('deleteTodo')
    this.$off('clearDone')
    this.$off('changeAll')
    this.$off('doneEdit')
    this.$off('changeStatus')
  },
  watch: {
    todoList: {
      handler(newVal) {
        localStorage.setItem('todoList', JSON.stringify(newVal))
      },
      deep: true,
    }
  },

}
</script>

<template>
  <div class="App">
    <TestHeader/>
    <TestList v-show="todoList.length>0" :todoList="todoList" />
    <TestFooter v-show="todoList.length>0"  :todoList="todoList"/>
  </div>
</template>

<style scoped>
.App {
  text-align: center;
  width: 50%;
  height: 100%;
  border: 2px solid #f3f3f3;
  border-radius: 20px;
  padding: 30px;
  background: #f8f8f8;
  margin: 0 auto;
}
</style>